<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>旅游攻略 - 探索世界</title>
  <!-- 优化：移除外部Font Awesome依赖，使用本地资源或内联SVG -->
  <link rel="stylesheet" href="/css/index.css">
  <style>
    /* 原有样式保持不变 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Helvetica Neue', Arial, sans-serif;
    }

    body {
      background-color: #f8f9fa;
      color: #333;
      line-height: 1.6;
    }

    a {
      text-decoration: none;
      color: inherit;
    }

    ul {
      list-style: none;
    }

    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 15px;
    }

    .btn {
      display: inline-block;
      padding: 10px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    .btn:hover {
      background-color: #45a049;
    }

    .section-title {
      text-align: center;
      margin-bottom: 30px;
      font-size: 28px;
      color: #2c3e50;
      position: relative;
      padding-bottom: 15px;
    }

    .section-title:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 80px;
      height: 3px;
      background-color: #4CAF50;
    }

    header {
      background-color: white;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      position: sticky;
      top: 0;
      z-index: 1000;
    }

    .header-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 0;
    }

    .logo {
      font-size: 24px;
      font-weight: bold;
      color: #4CAF50;
    }

    .logo span {
      color: #2c3e50;
    }

    nav ul {
      display: flex;
    }

    nav ul li {
      margin-left: 20px;
    }

    nav ul li a {
      padding: 5px 10px;
      transition: color 0.3s;
    }

    nav ul li a:hover {
      color: #4CAF50;
    }

    .auth-buttons {
      display: flex;
      gap: 10px;
    }

    .auth-buttons .btn {
      padding: 8px 15px;
    }

    .btn-login {
      background-color: transparent;
      color: #4CAF50;
      border: 1px solid #4CAF50;
    }

    .btn-login:hover {
      background-color: #4CAF50;
      color: white;
    }

    .filter-section {
      background-color: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      margin: 20px 0;
    }

    .filter-row {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      margin-bottom: 15px;
    }

    .filter-item {
      display: flex;
      align-items: center;
    }

    .filter-item label {
      margin-right: 8px;
      font-weight: bold;
    }

    .filter-item input,
    .filter-item select {
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    .search-btn {
      padding: 8px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    .guides-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
      gap: 25px;
      margin: 30px 0;
    }

    .guide-card {
      background-color: white;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      transition: transform 0.3s;
      cursor: pointer;
    }

    .guide-card:hover {
      transform: translateY(-5px);
    }

    .guide-image {
      height: 200px;
      overflow: hidden;
    }

    .guide-image img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.5s;
    }

    .guide-card:hover .guide-image img {
      transform: scale(1.05);
    }

    .guide-content {
      padding: 20px;
    }

    .guide-title {
      font-size: 18px;
      margin-bottom: 10px;
      color: #2c3e50;
    }

    .guide-meta {
      display: flex;
      justify-content: space-between;
      color: #888;
      font-size: 14px;
      margin-bottom: 15px;
    }

    .guide-destination {
      color: #4CAF50;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .guide-stats {
      display: flex;
      gap: 15px;
      color: #888;
      font-size: 14px;
    }

    .guide-stats span {
      display: flex;
      align-items: center;
    }

    /* 优化：使用CSS图标替代Font Awesome */
    .icon-eye:before {
      content: "👁";
      margin-right: 5px;
    }

    .icon-heart:before {
      content: "❤";
      margin-right: 5px;
    }

    .icon-clock:before {
      content: "⏱";
      margin-right: 5px;
    }

    .icon-marker:before {
      content: "📍";
      margin-right: 5px;
    }

    .icon-user:before {
      content: "👤";
      margin-right: 5px;
    }

    .icon-calendar:before {
      content: "📅";
      margin-right: 5px;
    }

    .icon-arrow-left:before {
      content: "←";
    }

    .icon-close:before {
      content: "✕";
    }

    .icon-upload:before {
      content: "📤";
    }

    .guide-excerpt {
      color: #666;
      margin: 15px 0;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .pagination {
      display: flex;
      justify-content: center;
      margin: 40px 0;
    }

    .loading {
      text-align: center;
      padding: 40px 0;
    }

    .loading-spinner {
      border: 4px solid #f3f3f3;
      border-top: 4px solid #4CAF50;
      border-radius: 50%;
      width: 40px;
      height: 40px;
      animation: spin 2s linear infinite;
      margin: 0 auto 15px;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .empty-state {
      text-align: center;
      padding: 60px 0;
      color: #888;
    }

    .empty-state i {
      font-size: 60px;
      margin-bottom: 20px;
      color: #ddd;
    }

    .guide-detail-container {
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      margin: 30px 0;
      padding: 30px;
    }

    .guide-detail-header {
      margin-bottom: 30px;
    }

    .guide-detail-title {
      font-size: 32px;
      color: #2c3e50;
      margin-bottom: 15px;
    }

    .guide-detail-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #888;
      margin-bottom: 20px;
      flex-wrap: wrap;
    }

    .guide-detail-author, .guide-detail-date, .guide-detail-stats {
      display: flex;
      align-items: center;
      margin-right: 20px;
      margin-bottom: 10px;
    }

    .guide-detail-author i, .guide-detail-date i, .guide-detail-stats i {
      margin-right: 5px;
      color: #4CAF50;
    }

    .guide-detail-destination {
      font-size: 18px;
      color: #4CAF50;
      margin-bottom: 20px;
      display: flex;
      align-items: center;
    }

    .guide-detail-destination i {
      margin-right: 8px;
    }

    .guide-detail-info {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      margin-bottom: 30px;
      padding: 15px;
      background-color: #f9f9f9;
      border-radius: 6px;
    }

    .detail-info-item {
      display: flex;
      flex-direction: column;
    }

    .detail-info-label {
      font-size: 12px;
      color: #888;
      margin-bottom: 5px;
    }

    .detail-info-value {
      font-size: 16px;
      font-weight: bold;
      color: #2c3e50;
    }

    .guide-detail-image {
      width: 100%;
      height: 400px;
      overflow: hidden;
      border-radius: 8px;
      margin-bottom: 30px;
    }

    .guide-detail-image img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .guide-detail-content {
      font-size: 16px;
      line-height: 1.8;
      color: #444;
    }

    .guide-detail-content p {
      margin-bottom: 20px;
    }

    .back-button {
      margin-bottom: 20px;
    }

    /* 图片画廊样式 */
    .image-gallery {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 15px;
      margin: 20px 0;
    }

    .gallery-item {
      height: 200px;
      overflow: hidden;
      border-radius: 8px;
      cursor: pointer;
    }

    .gallery-item img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s;
    }

    .gallery-item:hover img {
      transform: scale(1.05);
    }

    /* 投稿按钮样式 */
    .btn-submit {
      background-color: #ff9800;
      margin-left: 10px;
    }

    .btn-submit:hover {
      background-color: #f57c00;
    }

    /* 投稿弹窗样式 */
    .submit-modal {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 2000;
    }

    .modal-content {
      background-color: white;
      border-radius: 8px;
      width: 90%;
      max-width: 700px;
      max-height: 90vh;
      overflow-y: auto;
      padding: 30px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    }

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
    }

    .modal-title {
      font-size: 24px;
      color: #2c3e50;
    }

    .close-btn {
      background: none;
      border: none;
      font-size: 24px;
      cursor: pointer;
      color: #888;
    }

    .close-btn:hover {
      color: #333;
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: bold;
      color: #2c3e50;
    }

    .form-group input,
    .form-group select,
    .form-group textarea {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 16px;
    }

    .form-group textarea {
      min-height: 150px;
      resize: vertical;
    }

    .form-actions {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-top: 30px;
    }

    .btn-cancel {
      background-color: #f0f0f0;
      color: #333;
    }

    .btn-cancel:hover {
      background-color: #e0e0e0;
    }

    .btn-submit-form {
      background-color: #4CAF50;
      color: white;
    }

    .btn-submit-form:hover {
      background-color: #45a049;
    }

    @media (max-width: 768px) {
      .header-container {
        flex-direction: column;
      }

      nav ul {
        margin: 15px 0;
      }

      .filter-row {
        flex-direction: column;
      }

      .guides-list {
        grid-template-columns: 1fr;
      }

      .guide-detail-title {
        font-size: 24px;
      }

      .guide-detail-image {
        height: 250px;
      }

      .image-gallery {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      }

      .modal-content {
        width: 95%;
        padding: 20px;
      }
    }
    /* 页脚样式 */
    html, body {
      height: 100%;
    }

    body {
      display: flex;
      flex-direction: column;
      min-height: 100vh;
    }

    main {
      flex: 1 0 auto;
    }

    footer {
      background-color: #2c3e50;
      color: white;
      padding: 60px 0 20px;
      flex-shrink: 0;
    }

    .footer-content {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 30px;
      margin-bottom: 40px;
    }

    .footer-column h3 {
      margin-bottom: 20px;
      font-size: 18px;
    }

    .footer-column ul li {
      margin-bottom: 10px;
    }

    .footer-column ul li a:hover {
      color: #4CAF50;
    }

    .social-icons {
      display: flex;
      gap: 15px;
      margin-top: 15px;
    }

    .social-icons a {
      display: inline-block;
      width: 40px;
      height: 40px;
      background-color: rgba(255, 255, 255, 0.1);
      border-radius: 50%;
      text-align: center;
      line-height: 40px;
      transition: background-color 0.3s;
    }

    .social-icons a:hover {
      background-color: #4CAF50;
    }

    .copyright {
      text-align: center;
      padding-top: 20px;
      border-top: 1px solid rgba(255, 255, 255, 0.1);
      font-size: 14px;
    }
  </style>
</head>
<body>
<main>
<!-- 头部导航 -->
<header>
  <div class="container header-container">
    <div class="logo">
      <a href="index.html">探索<span>世界</span></a>
    </div>
    <nav>
      <ul>
        <li><a href="index.html">首页</a></li>
        <li><a href="scenic.html">景区</a></li>
        <li><a href="dot.html">景点</a></li>
        <li><a href="order.html">订单</a></li>
        <li><a href="guide.html"style="color: #4CAF50; font-weight: bold;" >攻略</a></li>
        <li><a href="notes.html">游记</a></li>
      </ul>
    </nav>
    <!-- 添加投稿按钮 -->
    <button class="btn btn-submit" id="submitGuideBtn">投稿</button>
    <div class="auth-buttons" id="authButtons">
      <!-- 登录状态由JavaScript动态生成 -->
    </div>
  </div>
</header>


<!-- 主要内容区域 -->
<div class="container">
  <h2 class="section-title">旅游攻略</h2>

  <!-- 筛选区域 -->
  <div class="filter-section">
    <div class="filter-row">
      <div class="filter-item">
        <label for="destination">目的地：</label>
        <input type="text" id="destination" placeholder="输入目的地">
      </div>
      <div class="filter-item">
        <label for="days">游玩天数：</label>
        <select id="days">
          <option value="">全部</option>
          <option value="1">1天</option>
          <option value="2">2天</option>
          <option value="3">3天</option>
          <option value="4">4天及以上</option>
        </select>
      </div>
      <div class="filter-item">
        <label for="season">推荐季节：</label>
        <select id="season">
          <option value="">全部</option>
          <option value="春季">春季</option>
          <option value="夏季">夏季</option>
          <option value="秋季">秋季</option>
          <option value="冬季">冬季</option>
        </select>
      </div>
    </div>
    <div class="filter-row">
      <!-- 修改：人均预算改为输入框 -->
      <div class="filter-item">
        <label for="budget">人均预算：</label>
        <input type="number" id="budget" placeholder="输入预算金额">
      </div>
      <div class="filter-item">
        <label for="sort">排序：</label>
        <select id="sort">
          <option value="updateTime">最新发布</option>
          <option value="viewCount">最多浏览</option>
          <option value="likeCount">最多点赞</option>
        </select>
      </div>
      <button class="search-btn" id="searchBtn">搜索</button>
    </div>
  </div>
  <!-- 攻略列表 -->
  <div id="guides-container">
    <div class="loading" v-if="loading">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <div class="empty-state" v-else-if="guides.length === 0">
      <i class="fas fa-map-marked-alt"></i>
      <p>暂无攻略，去发布一条吧~</p>
    </div>

    <!-- 攻略列表视图 -->
    <div v-if="!showDetail">
      <div class="guides-list">
        <div class="guide-card" v-for="guide in guides" :key="guide.guideId" @click="viewGuideDetail(guide.guideId)">
          <div class="guide-image">
            <!-- 实现图片懒加载 -->
            <img :src="getLazyImageUrl()" :data-src="getGuideImage(guide)" :alt="guide.title" @error="handleImageError" class="lazy-image">
          </div>
          <div class="guide-content">
            <h3 class="guide-title">{{ guide.title }}</h3>
            <div class="guide-meta">
              <!-- 修复作者显示问题 -->
              <span>作者:{{ guide.visitorsName || '用户' + guide.visitorId }}</span>
              <span>{{ formatDate(guide.updateTime) }}</span>
            </div>
            <div class="guide-destination">
              <i class="icon-marker"></i> {{ guide.destination }}
            </div>
            <div class="guide-stats">
              <span><i class="icon-eye"></i> {{ guide.viewCount }} 浏览</span>
              <span><i class="icon-heart"></i> {{ guide.likeCount }} 点赞</span>
              <span><i class="icon-clock"></i> {{ guide.days }} 天</span>
            </div>
            <p class="guide-excerpt">{{ guide.content ? guide.content.substring(0, 100) + '...' : '暂无内容介绍' }}</p>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="!loading && guides.length > 0">
        <el-pagination
                background
                layout="prev, pager, next"
                :total="total"
                :page-size="pageSize"
                :current-page="currentPage"
                @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>

    <!-- 攻略详情视图 -->
    <div v-else class="guide-detail-container">
      <el-button class="back-button" icon="el-icon-arrow-left" @click="goBackToList">返回列表</el-button>

      <div v-if="currentGuide">
        <div class="guide-detail-header">
          <h1 class="guide-detail-title">{{ currentGuide.title }}</h1>
          <div class="guide-detail-meta">
            <div class="guide-detail-author">
              <i class="icon-user"></i>
              <!-- 修复作者显示问题 -->
              <span>作者: {{ currentGuide.visitorsName || '用户' + currentGuide.visitorId }}</span>
            </div>
            <div class="guide-detail-date">
              <i class="icon-calendar"></i>
              <span>发布时间: {{ formatDate(currentGuide.updateTime) }}</span>
            </div>
            <div class="guide-detail-stats">
              <span><i class="icon-eye"></i> {{ currentGuide.viewCount }} 浏览</span>
              <span style="margin-left: 15px;"><i class="icon-heart"></i> {{ currentGuide.likeCount }} 点赞</span>
            </div>
          </div>
          <div class="guide-detail-destination">
            <i class="icon-marker"></i> {{ currentGuide.destination }}
          </div>
        </div>

        <div class="guide-detail-info">
          <div class="detail-info-item">
            <span class="detail-info-label">推荐游玩天数</span>
            <span class="detail-info-value">{{ currentGuide.days }} 天</span>
          </div>
          <div class="detail-info-item">
            <span class="detail-info-label">人均预算</span>
            <span class="detail-info-value">{{ currentGuide.budget }} 元</span>
          </div>
          <div class="detail-info-item">
            <span class="detail-info-label">推荐季节</span>
            <span class="detail-info-value">{{ currentGuide.season }}</span>
          </div>
        </div>

        <!-- 修复图片显示问题 - 显示所有图片 -->
        <div class="image-gallery" v-if="currentGuide.images && currentGuide.images.length > 0">
          <div class="gallery-item" v-for="(image, index) in currentGuide.images" :key="index">
            <!-- 详情页图片也实现懒加载 -->
            <img :src="getLazyImageUrl()" :data-src="image.imageUrl" :alt="'攻略图片' + (index + 1)" @error="handleImageError" class="lazy-image">
          </div>
        </div>

        <div class="guide-detail-content" v-html="formatContent(currentGuide.content)"></div>
      </div>

      <div v-else class="loading">
        <div class="loading-spinner"></div>
        <p>加载攻略详情中...</p>
      </div>
    </div>
  </div>
</div>
</main>
<!-- 页脚 -->
<footer>
        <div class="copyright">
            <p>© 2023 探索世界旅游网 版权所有</p>
        </div>
</footer>
<!-- 投稿弹窗 -->
<div id="submitModal" class="submit-modal" style="display: none;">
  <div class="modal-content">
    <div class="modal-header">
      <h2 class="modal-title">投稿旅游攻略</h2>
      <button class="close-btn" id="closeModalBtn">&times;</button>
    </div>
    <form id="guideForm">
      <div class="form-group">
        <label for="guideTitle">攻略标题 *</label>
        <input type="text" id="guideTitle" name="title" required placeholder="请输入攻略标题">
      </div>
      <div class="form-group">
        <label for="guideDestination">目的地 *</label>
        <input type="text" id="guideDestination" name="destination" required placeholder="请输入目的地">
      </div>
      <div class="form-group">
        <label for="guideDays">推荐游玩天数 *</label>
        <select id="guideDays" name="days" required>
          <option value="">请选择天数</option>
          <option value="1">1天</option>
          <option value="2">2天</option>
          <option value="3">3天</option>
          <option value="4">4天及以上</option>
        </select>
      </div>
      <div class="form-group">
        <label for="guideSeason">推荐季节 *</label>
        <select id="guideSeason" name="season" required>
          <option value="">请选择季节</option>
          <option value="春季">春季</option>
          <option value="夏季">夏季</option>
          <option value="秋季">秋季</option>
          <option value="冬季">冬季</option>
        </select>
      </div>

      <!-- 修改：人均预算改为输入框 -->
      <div class="form-group">
        <label for="guideBudget">人均预算（元） *</label>
        <input type="number" id="guideBudget" name="budget" required placeholder="请输入人均预算金额">
      </div>

      <!-- 新增：图片上传区域 -->
      <div class="form-group">
        <label>上传图片（可多选）</label>
        <div class="image-upload-area" id="imageUploadArea">
          <i class="icon-upload"></i>
          <p>点击或拖拽图片到此处上传</p>
          <p style="font-size: 12px; color: #888;">支持 JPG、PNG 格式，最多10张图片</p>
          <input type="file" id="imageInput" multiple accept="image/*" style="display: none;">
        </div>
        <div class="uploaded-images" id="uploadedImages"></div>
        <div class="image-upload-progress" id="uploadProgress" style="display: none;"></div>
      </div>

      <div class="form-group">
        <label for="guideContent">攻略内容 *</label>
        <textarea id="guideContent" name="content" required placeholder="请详细描述您的旅游攻略..."></textarea>
      </div>
      <div class="form-actions">
        <button type="button" class="btn btn-cancel" id="cancelBtn">取消</button>
        <button type="submit" class="btn btn-submit-form">提交</button>
      </div>
    </form>
  </div>
</div>

<!-- 引入Vue和Element UI -->
<script src="/js/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<!-- 引入axios -->
<script src="/js/axios.min.js"></script>

<script>
  // 获取当前用户信息
  function getCurrentUser() {
    // 从localStorage获取实际的用户信息
    const userInfoStr = localStorage.getItem('userInfo');
    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr);
        return {
          visitorId: userInfo.visitorId,
          visitorsName: userInfo.visitorsName
        };
      } catch (e) {
        console.error('解析用户信息失败:', e);
      }
    }

    // 如果没有获取到用户信息，重定向到登录页面
    alert('请先登录后再投稿');
    window.location.href = 'login.html';
    return null;
  }

  // 投稿弹窗控制
  document.addEventListener('DOMContentLoaded', function() {
    const submitBtn = document.getElementById('submitGuideBtn');
    const modal = document.getElementById('submitModal');
    const closeBtn = document.getElementById('closeModalBtn');
    const cancelBtn = document.getElementById('cancelBtn');
    const guideForm = document.getElementById('guideForm');
    const imageUploadArea = document.getElementById('imageUploadArea');
    const imageInput = document.getElementById('imageInput');
    const uploadedImages = document.getElementById('uploadedImages');
    const uploadProgress = document.getElementById('uploadProgress');

    let uploadedImageUrls = []; // 存储上传成功的图片URL

    // 打开弹窗
    submitBtn.addEventListener('click', function() {
      const currentUser = getCurrentUser();
      if (!currentUser) return;

      modal.style.display = 'flex';
      // 重置图片上传区域
      uploadedImages.innerHTML = '';
      uploadedImageUrls = [];
      uploadProgress.style.display = 'none';

      // 添加上传区域样式
      imageUploadArea.style.border = '2px dashed #ddd';
      imageUploadArea.style.padding = '20px';
      imageUploadArea.style.textAlign = 'center';
      imageUploadArea.style.cursor = 'pointer';
      imageUploadArea.style.borderRadius = '4px';
      imageUploadArea.innerHTML = `
            <i class="icon-upload" style="font-size: 48px; color: #ddd; margin-bottom: 10px;"></i>
            <p>点击或拖拽图片到此处上传</p>
            <p style="font-size: 12px; color: #888;">支持 JPG、PNG 格式，最多5张图片，每张不超过10MB</p>
        `;
    });

    // 关闭弹窗
    function closeModal() {
      modal.style.display = 'none';
      guideForm.reset();
      uploadedImages.innerHTML = '';
      uploadedImageUrls = [];
      uploadProgress.style.display = 'none';
    }

    closeBtn.addEventListener('click', closeModal);
    cancelBtn.addEventListener('click', closeModal);

    // 点击弹窗外部关闭
    modal.addEventListener('click', function(e) {
      if (e.target === modal) {
        closeModal();
      }
    });

    // 图片上传功能
    imageUploadArea.addEventListener('click', function() {
      imageInput.click();
    });

    // 拖拽上传功能
    imageUploadArea.addEventListener('dragover', function(e) {
      e.preventDefault();
      imageUploadArea.style.borderColor = '#4CAF50';
      imageUploadArea.style.backgroundColor = '#f9f9f9';
    });

    imageUploadArea.addEventListener('dragleave', function() {
      imageUploadArea.style.borderColor = '#ddd';
      imageUploadArea.style.backgroundColor = 'transparent';
    });

    imageUploadArea.addEventListener('drop', function(e) {
      e.preventDefault();
      imageUploadArea.style.borderColor = '#ddd';
      imageUploadArea.style.backgroundColor = 'transparent';

      const files = e.dataTransfer.files;
      handleImageFiles(files);
    });

    imageInput.addEventListener('change', function(e) {
      handleImageFiles(e.target.files);
    });

    // 处理图片文件 - 单张上传
    function handleImageFiles(files) {
      if (files.length === 0) return;

      // 限制上传数量
      if (uploadedImageUrls.length + files.length > 5) {
        alert('最多只能上传5张图片');
        return;
      }

      uploadProgress.style.display = 'block';

      // 逐个上传文件
      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 验证文件类型
        if (!file.type.startsWith('image/')) {
          alert('请上传图片文件（JPG/PNG格式）');
          continue;
        }

        // 验证文件大小
        if (file.size > 10 * 1024 * 1024) {
          alert('图片大小不能超过10MB');
          continue;
        }

        uploadProgress.textContent = `正在上传图片 ${i + 1}/${files.length}...`;

        uploadSingleImage(file)
                .then(imageUrl => {
                  uploadedImageUrls.push(imageUrl);
                  addImageToPreview(imageUrl);
                  uploadProgress.textContent = `已上传 ${uploadedImageUrls.length} 张图片`;
                })
                .catch(error => {
                  console.error('图片上传失败:', error);
                  uploadProgress.textContent = `图片上传失败: ${error.message}`;
                });
      }
    }

    // 单张图片上传函数
    function uploadSingleImage(file) {
      return new Promise((resolve, reject) => {
        const formData = new FormData();
        formData.append('file', file);

        // 使用正确的上传接口
        axios.post('/guideImages/uploadImage', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
                .then(response => {
                  if (response.data.code === 200) {
                    // 根据后端返回的数据结构获取URL
                    const imageUrl = response.data.data.url || response.data.data;
                    resolve(imageUrl);
                  } else {
                    reject(new Error(response.data.msg || '上传失败'));
                  }
                })
                .catch(error => {
                  reject(error);
                });
      });
    }

    // 添加图片预览
    function addImageToPreview(imageUrl) {
      const imageDiv = document.createElement('div');
      imageDiv.className = 'uploaded-image';
      imageDiv.style.display = 'inline-block';
      imageDiv.style.margin = '10px';
      imageDiv.style.position = 'relative';
      imageDiv.style.width = '100px';
      imageDiv.style.height = '100px';
      imageDiv.style.overflow = 'hidden';
      imageDiv.style.borderRadius = '4px';
      imageDiv.style.border = '1px solid #ddd';

      imageDiv.innerHTML = `
            <img src="${imageUrl}" alt="预览图片" style="width: 100%; height: 100%; object-fit: cover;">
            <button type="button" class="remove-image" style="position: absolute; top: 5px; right: 5px; background: rgba(0,0,0,0.5); color: white; border: none; border-radius: 50%; width: 20px; height: 20px; cursor: pointer;">&times;</button>
        `;

      // 移除图片
      imageDiv.querySelector('.remove-image').addEventListener('click', function(e) {
        e.stopPropagation();
        const index = uploadedImageUrls.indexOf(imageUrl);
        if (index > -1) {
          uploadedImageUrls.splice(index, 1);
        }
        imageDiv.remove();
        uploadProgress.textContent = `已上传 ${uploadedImageUrls.length} 张图片`;
      });

      uploadedImages.appendChild(imageDiv);
    }

    // 表单提交
    guideForm.addEventListener('submit', function(e) {
      e.preventDefault();

      const currentUser = getCurrentUser();
      if (!currentUser) return;

      // 获取表单数据
      const formData = new FormData(guideForm);
      const budgetValue = parseInt(formData.get('budget')) || 0;

      const guideData = {
        title: formData.get('title'),
        destination: formData.get('destination'),
        days: parseInt(formData.get('days')) || 1,
        season: formData.get('season'),
        budget: budgetValue.toString(),
        content: formData.get('content'),
        visitorId: currentUser.visitorId,
        visitorsName: currentUser.visitorsName,
        status: '审核中',
        viewCount: 0,
        likeCount: 0,
        createTime: new Date(),
        updateTime: new Date()
      };

      // 先保存攻略基本信息
      axios.post('/guides/add', guideData)
              .then(response => {
                if (response.data.code === 200) {
                  const guideId = response.data.data; // 获取返回的攻略ID

                  // 如果有上传的图片，保存图片关联
                  if (uploadedImageUrls.length > 0) {
                    return saveGuideImages(guideId, uploadedImageUrls);
                  } else {
                    return Promise.resolve();
                  }
                } else {
                  throw new Error(response.data.msg || '投稿失败');
                }
              })
              .then(() => {
                alert('攻略投稿成功！正在审核中...');
                closeModal();
                if (typeof app !== 'undefined') {
                  app.fetchGuides();
                }
              })
              .catch(error => {
                console.error('投稿失败:', error);
                alert('投稿失败：' + error.message);
              });
    });

// 保存攻略图片关联
    function saveGuideImages(guideId, imageUrls) {
      const imagePromises = imageUrls.map(imageUrl => {
        const imageData = {
          guideId: guideId,
          imageUrl: imageUrl,
          uploadTime: new Date()
        };

        return axios.post('/guideImages/add', imageData);
      });

      return Promise.all(imagePromises);
    }

    // Vue应用
    const app = new Vue({
      el: '#guides-container',
      data: {
        guides: [],
        currentGuide: null,
        loading: true,
        total: 0,
        pageSize: 9,
        currentPage: 1,
        showDetail: false,
        filters: {
          destination: '',
          days: '',
          season: '',
          budget: '',
          sort: 'updateTime'
        }
      },
      mounted() {
        // 检查URL参数，如果存在guideId则直接显示详情
        const urlParams = new URLSearchParams(window.location.search);
        const guideId = urlParams.get('guideId');
        
        if (guideId) {
          // 如果存在guideId参数，直接显示攻略详情
          this.viewGuideDetail(guideId);
        } else {
          // 否则显示攻略列表
          this.fetchGuides();
        }

        // 设置筛选事件监听
        document.getElementById('searchBtn').addEventListener('click', () => {
          this.applyFilters();
        });

        // 监听筛选条件变化
        document.getElementById('destination').addEventListener('change', (e) => {
          this.filters.destination = e.target.value;
        });

        document.getElementById('days').addEventListener('change', (e) => {
          this.filters.days = e.target.value;
        });

        document.getElementById('season').addEventListener('change', (e) => {
          this.filters.season = e.target.value;
        });

        document.getElementById('budget').addEventListener('change', (e) => {
          this.filters.budget = e.target.value;
        });

        document.getElementById('sort').addEventListener('change', (e) => {
          this.filters.sort = e.target.value;
          this.applyFilters();
        });

        // 初始化图片懒加载
        this.initLazyLoading();
      },
      methods: {
        // 获取攻略列表
        fetchGuides() {
          this.loading = true;

          const requestData = {
            pageNo: this.currentPage,
            pageSize: this.pageSize,
            data: this.filters
          };

          axios.post('/guides/queryByPage', requestData)
                  .then(response => {
                    if (response.data.code === 200) {
                      this.guides = response.data.data.list || [];
                      this.total = response.data.data.total || 0;

                      // 为每个攻略获取图片
                      this.guides.forEach(guide => {
                        this.fetchGuideImages(guide);
                      });
                    } else {
                      console.error('获取攻略列表失败:', response.data.msg);
                      this.guides = [];
                    }
                    this.loading = false;
                  })
                  .catch(error => {
                    console.error('请求失败:', error);
                    this.loading = false;
                    this.guides = [];
                  });
        },

        // 获取攻略图片
        fetchGuideImages(guide) {
          axios.post('/guideImages/queryByPage', {
            pageNo: 1,
            pageSize: 10,
            data: { guideId: guide.guideId }
          })
                  .then(response => {
                    if (response.data.code === 200 && response.data.data) {
                      // 直接设置攻略的图片数据
                      this.$set(guide, 'images', response.data.data.list || []);

                      // 在图片数据加载完成后初始化懒加载
                      this.$nextTick(() => {
                        this.initLazyLoading();
                      });
                    }
                  })
                  .catch(error => {
                    console.error('获取攻略图片失败:', error);
                  });
        },

        // 查看攻略详情
        viewGuideDetail(guideId) {
          // 检查是否在详情页中，如果是则使用Vue路由而不是页面跳转
          if (this.showDetail !== undefined) {
            this.showDetail = true;
            this.loading = true;

            // 调用queryById接口获取攻略详情
            axios.get('/guides/queryById?guideId=' + guideId)
                    .then(response => {
                      if (response.data.code === 200 && response.data.data) {
                        this.currentGuide = response.data.data;

                        // 增加浏览量
                        this.increaseViewCount(guideId);

                        // 在详情加载完成后重新初始化懒加载
                        this.$nextTick(() => {
                          this.initLazyLoading();
                        });
                      } else {
                        console.error('获取攻略详情失败:', response.data.msg);
                        this.$message.error('获取攻略详情失败');
                      }
                      this.loading = false;
                    })
                    .catch(error => {
                      console.error('请求失败:', error);
                      this.$message.error('加载攻略详情失败');
                      this.loading = false;
                    });
          } else {
            // 如果不在Vue组件中，使用页面跳转
            window.location.href = 'guide.html?guideId=' + guideId;
          }
        },

        // 增加浏览量
        increaseViewCount(guideId) {
          axios.post('/guides/view', { guideId: guideId })
                  .catch(error => {
                    console.error('增加浏览量失败:', error);
                  });
        },

        // 返回列表
        goBackToList() {
          this.showDetail = false;
          this.currentGuide = null;
          this.$nextTick(() => {
            this.initLazyLoading();
          });
        },

        // 应用筛选条件
        applyFilters() {
          this.currentPage = 1;
          this.fetchGuides();
        },

        // 处理分页变化
        handlePageChange(page) {
          this.currentPage = page;
          this.fetchGuides();
          window.scrollTo(0, 0);
        },

        // 获取攻略图片
        getGuideImage(guide) {
          // 从攻略数据中直接获取图片
          if (guide.images && guide.images.length > 0) {
            // 返回第一张图片的完整URL路径
            return guide.images[0].imageUrl;
          }

          // 使用本地默认图片
          return '/img/guideImages/default.jpg';
        },

        // 处理图片加载错误
        handleImageError(event) {
          // 使用本地默认图片
          event.target.src = '/img/guideImages/default.jpg';
          event.target.classList.remove('lazy-image');
        },

        // 获取攻略详情图片 - 修复方法
        fetchGuideDetailImages(guideId) {
          if (!guideId) return;

          axios.post('/guideImages/queryByPage', {
            pageNo: 1,
            pageSize: 20, // 增加页面大小以获取更多图片
            data: { guideId: guideId }
          })
                  .then(response => {
                    if (response.data.code === 200 && response.data.data) {
                      this.$set(this.currentGuide, 'images', response.data.data.list || []);

                      // 初始化懒加载
                      this.$nextTick(() => {
                        this.initLazyLoading();
                      });
                    }
                  })
                  .catch(error => {
                    console.error('获取攻略图片失败:', error);
                  });
        },

        // 获取懒加载占位图片URL
        getLazyImageUrl() {
          // 返回一个极小的透明PNG图片作为占位符(base64编码)
          return '';
        },

        // 初始化图片懒加载
        initLazyLoading() {
          // 使用Intersection Observer实现懒加载
          if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver((entries, observer) => {
              entries.forEach(entry => {
                if (entry.isIntersecting) {
                  const img = entry.target;
                  const src = img.dataset.src;
                  if (src) {
                    img.src = src;
                    img.classList.remove('lazy-image');
                  }
                  observer.unobserve(img);
                }
              });
            });

            const lazyImages = document.querySelectorAll('.lazy-image');
            lazyImages.forEach(img => imageObserver.observe(img));
          } else {
            // 降级处理：如果浏览器不支持Intersection Observer，则直接加载图片
            const lazyImages = document.querySelectorAll('.lazy-image');
            lazyImages.forEach(img => {
              const src = img.dataset.src;
              if (src) {
                img.src = src;
                img.classList.remove('lazy-image');
              }
            });
          }
        },

        // 格式化日期
        formatDate(dateString) {
          if (!dateString) return '未知日期';
          const date = new Date(dateString);
          return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        },

        // 格式化内容
        formatContent(content) {
          if (!content) return '<p>暂无内容</p>';
          // 将换行符转换为HTML段落
          return content.replace(/\n/g, '</p><p>').replace(/<p><\/p>/g, '');
        }
      }
    })
  });
  // 检查登录状态并更新导航栏
  function updateAuthButtons() {
    const authButtons = document.getElementById('authButtons');
    const cid = localStorage.getItem('cid');
    const userInfoStr = localStorage.getItem('userInfo');

    if (cid && userInfoStr) {
      // 用户已登录，显示个人中心和退出登录
      try {
        const userInfo = JSON.parse(userInfoStr);
        authButtons.innerHTML = `
                  <span style="margin-right: 15px; color: #4CAF50;">欢迎，${userInfo.visitorsName || userInfo.realName || '用户'}</span>
                  <a href="profile.html" class="btn">个人中心</a>
                  <a href="#" class="btn btn-login" onclick="logout()">退出登录</a>
              `;
      } catch (e) {
        // 解析用户信息失败，显示默认登录状态
        authButtons.innerHTML = `
                  <a href="login.html" class="btn btn-login">登录</a>
                  <a href="register.html" class="btn">注册</a>
              `;
      }
    } else {
      // 用户未登录，显示登录注册按钮
      authButtons.innerHTML = `
              <a href="login.html" class="btn btn-login">登录</a>
              <a href="register.html" class="btn">注册</a>
          `;
    }
  }

  // 通用的退出登录函数（用于导航栏）
  function logout() {
    if (confirm('确定要退出登录吗？')) {
      // 清除本地存储的用户信息
      localStorage.removeItem('cid');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('token');

      // 更新导航栏显示
      updateAuthButtons();

      // 延迟跳转到首页
      setTimeout(() => {
        window.location.href = 'index.html';
      }, 500);
    }
    return false; // 阻止链接默认行为
  }

  // 页面加载时更新导航栏状态
  document.addEventListener('DOMContentLoaded', function() {
    updateAuthButtons();
  });
</script>
</body>
</html>